package pers.vic.base.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.util.WebUtils;

import pers.vic.base.bo.system.Principal;
import pers.vic.base.contant.BaseConsoleConstant;
import pers.vic.base.handle.convert.DateEditor;
import pers.vic.base.pager.CommonLookup;
import pers.vic.base.pager.Lookup;
import pers.vic.base.tools.Tools;


public abstract class BaseConsoleController extends BaseController{
	

	/**登陆提示信息*/
	public static final String LOGIN_MSG = "loginMsg";
	
	/**
	 * Controller的日期参数的统一转化
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder){
		binder.registerCustomEditor(Date.class, new DateEditor());
	}
	
	
	/**
	 * 获得本controller的查询条件
	 */
	protected Lookup getLookup() throws IllegalStateException{
		String lookupKey = getClass().getName() + "." + BaseConsoleConstant.SESSIONKEY_SUFFIX_LOOKUP;
		Lookup lookup = getSessionAttribute(lookupKey);
		if(lookup == null) {
			lookup = instanceLookup();
			setSessionAttribute(lookupKey, lookup);
		}
		return lookup;
	}
	/**
	 * 获得本controller的查询条件
	 */
	protected Lookup getLookup(String prefix) throws IllegalStateException{
		String lookupKey = getClass().getName() + "." + BaseConsoleConstant.SESSIONKEY_SUFFIX_LOOKUP + prefix;
		Lookup lookup = getSessionAttribute(lookupKey);
		if(lookup == null) {
			lookup = instanceLookup();
			setSessionAttribute(lookupKey, lookup);
		}
		return lookup;
	}
	
	/**
	 * 保存提交的查询条件
	 */
	protected void setLookup(Lookup lookup) {
		setSessionAttribute(getClass().getName() + "." + BaseConsoleConstant.SESSIONKEY_SUFFIX_LOOKUP, lookup);
	}
	
	protected void setLookup(Lookup lookup, String prefix) {
		setSessionAttribute(getClass().getName() + "." + BaseConsoleConstant.SESSIONKEY_SUFFIX_LOOKUP + prefix, lookup);
	}
	/**
	 * 每个需要查询的controller都应该重写的方法 返回Lookup的子类
	 */
	protected Lookup instanceLookup() {
		return new CommonLookup();
	}


	/**
	 * 当前线程中的request  
	 */
	protected HttpServletRequest currentRequest() {
		return Tools.currentRequest();
	}

	/**
	 * 当前线程中的session 
	 */
	protected HttpSession currentSession() {
		return Tools.currentSession();
	}

	/**
	 * 设置session 
	 */
	protected void setSessionAttribute(String key, Object obj) throws IllegalStateException {
		WebUtils.setSessionAttribute(currentRequest(), key, obj);
	}

	/**
	 * 获取session中的对象  若当前无session则创建一个
	 */
	@SuppressWarnings("unchecked")
	protected <T> T getSessionAttribute(String key) throws IllegalStateException {
		return (T) WebUtils.getSessionAttribute(currentRequest(), key);
	}

	/**
	 * 获得session中的对象
	 */
	@SuppressWarnings("unchecked")
	protected <T> T getOrCreateSessionAttribute(String key, Class<T> clazz) throws IllegalStateException {
		HttpSession session = currentRequest().getSession();
//		return (T) WebUtils.getOrCreateSessionAttribute(session, key, clazz);
		return (T) getOrCreateSessionAttribute(session, key, clazz);
	}
	
	
	/**
	 * from spring4.x WebUtils.getOrCreateSessionAttribute
	 * @param session
	 * @param name
	 * @param clazz
	 * @return
	 * @throws IllegalArgumentException
	 */
	private static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz)
			throws IllegalArgumentException {

		Object sessionObject = session.getAttribute(name);
		if (sessionObject == null) {
			try {
				sessionObject = clazz.newInstance();
			}
			catch (InstantiationException ex) {
				throw new IllegalArgumentException(
					"Could not instantiate class [" + clazz.getName() +
					"] for session attribute '" + name + "': " + ex.getMessage());
			}
			catch (IllegalAccessException ex) {
				throw new IllegalArgumentException(
					"Could not access default constructor of class [" + clazz.getName() +
					"] for session attribute '" + name + "': " + ex.getMessage());
			}
			session.setAttribute(name, sessionObject);
		}
		return sessionObject;
	}
	
	public Map<String, String> getParamsMap(){
		Map<String, String> paramsMap = new HashMap<String, String>();
		HttpServletRequest request = currentRequest();
		if(request != null) {
			Map<String, String[]> params = request.getParameterMap();
			for(String key :params.keySet()) {
				paramsMap.put(key, StringUtils.join(params.get(key), ","));
			}
		}
		return paramsMap;
	}
	
	
	/**
	 * 获得当前线程中的登陆用户信息
	 * @return  有可能为null
	 */
	protected Principal getPrincipal() {
		try{
			return (Principal) currentSession().getAttribute(BaseConsoleConstant.USER_SESSION_KEY);
		}catch(Exception e) {
			return null;
		}
	}
	
	
}